<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model="qname" placeholder="请输入问卷名称" suffix-icon="search" style="width: 200px"/>
      <el-button id="21" type="primary" style="margin-left: 10px" @click="search">查询</el-button>
      <el-button id="22" type="success" @click="reset">重置</el-button>
      <el-button id="23" type="primary" style="margin-left: 10px" @click="add">新增问卷</el-button>
      <el-button id="24" type="warning" style="margin-left: 10px" @click="dataShow">数据查看</el-button>
      <el-icon @click="allQuestionnaireInfo" style="margin-left: 20px;margin-top:10px; cursor: pointer" :size="20" title="问卷批量答题情况" ><DataAnalysis /></el-icon>
    </div>
    <el-scrollbar>
      <el-table :data="tableData"  height="450" stripe style="width: 100%" >
        <el-table-column
            label="序号"
            type="index"
            width="75"
            align="center">
          <template v-slot="scope">
            <span>{{(currentPage - 1) * pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="qid" label="问卷id" width="150" align="center"/>
        <el-table-column prop="qname" label="问卷名称" width="150" align="center"/>
        <el-table-column prop="status" label="问卷状态" width="80" align="center">
          <template v-slot="scope">
            <el-switch  v-model="scope.row.status" active-value="1" inactive-value="0" @click="changeStatus(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="start" label="创建时间"  width="200" align="center"/>
        <el-table-column prop="end" label="结束时间"  width="200" align="center"/>
        <el-table-column prop="operation" label="操作" align="center">
          <template #default="scope">
<!--            把所有的按钮换成了图标，但是编辑和发布还没有函数所以是空的-->
            <el-icon @click="edit(scope.row)"  :size="20" style="margin-right: 10px;cursor: pointer;" title="编辑问卷" ><Edit /></el-icon>
            <el-icon @click="look(scope.row)" :size="20" style="margin-right: 10px;cursor: pointer;"  title="查看问卷"><View /></el-icon>
            <el-icon  @click="dele(scope.row)" :size="20" style="margin-right: 10px;cursor: pointer;"  title="删除问卷" ><Delete /></el-icon>
            <el-icon  @click="initial(scope.row)"   :size="20" style="margin-right: 10px;cursor: pointer;"  title="个性化问卷"><Setting /></el-icon>
            <el-icon @click="release(scope.row)" :size="20" style="margin-right: 10px;cursor: pointer;"  title="发布问卷"><Share /></el-icon>

            <el-dialog v-model="releaseVisible" title="发布问卷">
              <span>发布成功，问卷地址为：http://localhost:8080/answerLogin?qid={{qid}}</span>
              <template #footer>
                <span class="dialog-footer">
                  <el-button class="copy-btn2" type="primary" @click="copyURL(QID)">点我复制问卷</el-button>
                </span>
              </template>
            </el-dialog>
            <el-icon @click="lookResult(scope.row)"  :size="20" style="margin-right: 10px;cursor: pointer;"  title="题目统计"><PieChart /></el-icon>
            <el-icon @click="lookData(scope.row)" :size="20" style="margin-right: 10px;cursor: pointer;" title="查看问卷作答情况"><Histogram /></el-icon>
            <el-dialog v-model="dialogTableVisible" title="以下为该问卷作答情况：">
              <el-table :data="questionAnswerData">
                <el-table-column prop="qname" label="问卷名" width="250" />
                <el-table-column prop="answeredCount" label="作答人数" width="250" />
                <el-table-column prop="recyclingRate" label="作答率" width="250" />
              </el-table>
              <template #footer>
                  <el-button type="danger" @click="dialogTableVisible = false">关闭</el-button>
              </template>
            </el-dialog>
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    <div class='block'>
      <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="pageSize"
          layout="total,  prev, pager, next, jumper"
          :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog v-model="centerDialogVisible" title="请填写新问卷信息" width="30%" center>
      <el-form :model="form" label-width="120px">
        <el-form-item label="问卷名称">
          <el-input v-model="quesName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="问卷结束时间">
          <div class="block">
            <span class="demonstration"></span>
            <el-date-picker
                v-model="value1"
                type="date"
                placeholder="选择日期">
            </el-date-picker>
            <el-time-picker v-model="value2" placeholder="请选择时刻" />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">确认</el-button>
      </span>
      </template>
    </el-dialog>

<!--    抽屉，即侧边弹出的页面展示题目统计-->
    <el-drawer v-model="drawer" :direction="rtl" :with-header="true">

      <h3 style="position:fixed;top:0;margin-left: 150px">{{chosenquesName}}</h3>

      <template v-for="(item,index) in itemData" >
            <span>{{index+1+". " + item.questext}}</span>
        <div style="height: 20px"></div>
            <el-table :data="item.drawData" border stripe="true" style="width: 100%">

              <template v-for="items in tableHead[index]">
                <el-table-column :prop="items.column_name" :label="items.column_comment"  align="center" ></el-table-column>
              </template>
            </el-table>
          <br>
      </template>
    </el-drawer>
    <div style="text-align: right">
      <el-icon @click="speak" style="margin-right: 30px;margin-bottom: 80px ;cursor: pointer;"  title="联系管理员" :size="30"><ChatDotSquare /></el-icon>
    </div>

  </div>

<!--显示所有问卷的答题情况-->
  <el-dialog style="width: 600px" v-model="alldialogFormVisible" title="问卷答题情况" >

    <el-scrollbar>
      <el-table :data="allTableData"  height="450" stripe style="width: 100%" >
        <el-table-column
            label="序号"
            type="index"
            width="75"
            align="center">
          <template v-slot="scope">
            <span>{{(currentPage - 1) * pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="qname" label="问卷名称" width="150" align="center"/>
        <el-table-column prop="answeredCount" label="答题人数" width="150" align="center"/>
        <el-table-column prop="recyclingRate" label="回收率" width="150" align="center">
        </el-table-column>
      </el-table>
    </el-scrollbar>
  </el-dialog>
</template>

<script>
import {ElMessage} from "element-plus";
import router from "@/router";
import request from "@/util/request";
export default {
  name: "Questionnaire",
  data() {
    return {
      //分页器的属性
      pageSize:10,
      currentPage:1,
      total:0,
      QID:'',
      //单卷查看问卷作答情况
      dialogTableVisible:false,
      questionAnswerData:[{

      }
      ],
      //批量查看问卷作答情况
      alldialogFormVisible:false,
      allTableData:[],

      //发布问卷分享url
      releaseVisible:false,

      type:'0',
      tableHead:[],//等待赋值的表头
      tableHead1:[
          {//填空题的表头
          column_name: "answerContent", column_comment:"内容"
          }
      ],
      tableHead2:[   //选择题的表头
        {
          column_name: "answerContent",column_comment:"选项"
        },
        {
          column_name: "num",column_comment:"数量"
        },
        {
          column_name: "percentage",column_comment:"占比"
        },
      ],
      table:'',
      drawer:false,//抽屉的属性
      itemData:[],//动态表头--每个问题的内容
    // [{
    //  quesText:''
    //  drawData:[]
    // }]
      chosenquesName:'',


      tableData: [],
      qname: '',
      centerDialogVisible: false,
      form: {

      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      quesName:'',
      value1: '',
      value2:''
    }
  },
  methods: {
    dataShow(){
        router.push('/data')
    },
    allQuestionnaireInfo(){
        this.alldialogFormVisible=true
      request.post('/questionnaire/selectQuestionnaireDetail').then(res=>res.data).then(res=>{

        console.log(res)
        this.allTableData = res.data

      })
    },
    speak(){
      window.open('http://172.22.167.190:8081/222','_blank')
    },
    changeStatus(row){
      console.log(row.status)
      if(row.status === 0){
        row.status = 1;
      }
      else if(row.status === 1){
        row.status = 0;
      }
      this.$axios.post("http://localhost:8090/questionnaire/updateStatus", {qid:row.qid,status:row.status}).then(res => {
        console.log(res)
      })
    },
    lookData(row) {
      this.dialogTableVisible = true;
      var i = 0;
      let ans = [];
      this.$axios.post("http://localhost:8090/questionnaire/selectQuestionnaireDetail").then(res => {
        console.log(res)
        for(;i<res.data.data.length;i++){
          if(row.qname === res.data.data[i].qname){
            ans.push({qname: res.data.data[i].qname,answeredCount: res.data.data[i].answeredCount,recyclingRate: res.data.data[i].recyclingRate});
          }
        }
        this.questionAnswerData = ans;
      });
    },
    copyURL(qid) {
      var input = document.createElement("input");
      input.value = "http://localhost:8080/answerLogin?qid=" + qid;
      document.body.appendChild(input);
      input.select();
      document.execCommand("Copy");
      document.body.removeChild(input);
      this.$message.success('复制成功！');
      this.releaseVisible = false;
    },
    initial(row) {
      this.$cookies.set('qid', row.qid)
      this.$cookies.set('uid',this.$cookies.get("value").uid)
      router.push("/Individu")
    },
    search() {
      document.getElementById("21").blur();
      this.loadPost()
    },
    handleCurrentChange(val){
      console.log(`${val} items per page`)
      this.currentPage=val
      this.loadGet()
    },
    loadPost() {
      if (this.qname === '') {
        let formData = new FormData();
        let uid = this.$cookies.get('value').uid
        console.log(uid)
        formData.append("uid", uid);
        this.$axios.post("http://localhost:8090/questionnaire/queryQuesByUid",formData).then(res => res.data).then(res => {
          console.log(res)
          this.tableData = res.data[this.currentPage-1].records
          this.total=res.data[this.currentPage-1].total
        });
      } else {
        let formData = new FormData();
        formData.append("qid", this.qname);
        this.$axios.post("http://localhost:8090/questionnaire/findQuestionnaire", formData).then(res => {
          this.tableData = res.data.data
          console.log(res)
        });
      }
    },
    lookResult(row) {
      this.drawer = true
      this.chosenquesName = row.qname

      request.post("/question/quesStatistics", {
        qid: row.qid
      }).then(res => res.data).then(res => {
        console.log(res.data)
        let question = res.data.question
        let answerChoice = res.data.answerChoice
        let questionBlock = res.data.questionBlock
        this.itemData=[]
        this.tableHead=[]
        for (let i = 0; i < question.length; i++) {

          if (question[i].questionType == '1') {//如果这道题是选择题
            let choiceQuesText = question[i].questionText
            let choiceData = []
            //从所有选择题答案里面找到这个题号的答案，加到这个数组里面
            for (let j = 0; j < answerChoice.length; j++) {
              if (answerChoice[j].count === question[i].count) {
                choiceData.push(answerChoice[j])
              }
            }//选项的数组是否穿进来
            this.itemData.push({questext: choiceQuesText, drawData: choiceData})
            this.type='1'
            this.tableHead.push(this.tableHead2)
          } else {//这道题是填空题
            this.tableHead.push( this.tableHead1)//换成填空题的表头
            this.type='3'
            let quesText = question[i].questionText
            let blockData = []
            //从所有填空题答案里面找到这个题号的答案，加到这个数组里面
            for (let j = 0; j < questionBlock.length; j++) {
              if (questionBlock[j].count === question[i].count) {
                if(questionBlock[j].answerContent!==""){
                  blockData.push(questionBlock[j])

                }
              console.log(questionBlock[j])
              }
            }
            this.itemData.push({questext:quesText,drawData:blockData })

          }//填空选择结束

          console.log(this.itemData)
         console.log(this.tableHead)
        }
      });
    },
    add() {
      document.getElementById("23").blur();
      this.centerDialogVisible = true;
    },
    release(row) {
      console.log(row.status+"*")
      // request.post("/questionnaire/publish",{
      //   qid:row.qid
      // }).then(res=>{
      //   console.log(res.data)
      //   if(res.data.code=='200'){
      //     this.releaseVisible = true;
      //   }else if(row.status === "0"){
      //       ElMessage({
      //         message: '您还未设置个性化，请先设置个性化！',
      //         type: 'error',
      //       })
      //     }
      //
      // })
      if(row.status === "1"){

        this.releaseVisible = true;
        this.QID = row.qid;
      }
      else if(row.status === "0"){
        ElMessage({
          message: '该问卷还未开启，请先开启问卷再进行发布！！！',
          type: 'error',
        })
      }
    },
    look(row) {
      this.$cookies.set('qid', row.qid)
      router.push('/LookQuestionnaire')
    },
    reset() {
      document.getElementById("22").blur();
      let formData = new FormData();
      formData.append("uid", this.$cookies.get('uid'))
      this.$axios.get("http://localhost:8090/questionnaire/findQuestionnaireByUid", formData).then(res => {
        console.log(res)
        this.tableData = res.data.data
      });
    },
    save() {
      self.$cookies.remove('modelForm')
      this.centerDialogVisible = false
      var newDate = "";
      console.log(this.value2)
      var year = this.value1.getFullYear();
      var month = this.value1.getMonth() + 1 > 9 ? this.value1.getMonth() + 1 : "0" + (this.value1.getMonth() + 1);
      var day = this.value1.getDate() > 9 ? this.value1.getDate() : "0" + this.value1.getDate();
      var hour = this.value2.getHours() > 9 ? this.value2.getHours() : "0" + this.value2.getHours();
      var min = this.value2.getMinutes() > 9 ? this.value2.getMinutes() : "0" + this.value2.getMinutes();
      var sec = this.value2.getSeconds() > 9 ? this.value2.getSeconds() : "0" + this.value2.getSeconds();
      newDate = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec;
      this.$cookies.set('end', newDate);
      this.$cookies.set('quesName', this.quesName);
      router.push('/AddQuestionnaire')
    },
    dele(row) {
      let formData = new FormData();
      formData.append("qid", row.qid)

      this.$axios.post("http://localhost:8090/questionnaire/deleteQuestionnaire", {
        qid: row.qid
      }).then(res => {
        console.log("zheshiyigedata")
       console.log(res.data)
        if (res.data.code == '200') {
          ElMessage({
            message: '操作成功！',
            type: 'success',
          })
          this.loadPost()
        } else {
          ElMessage({
            message: '删除失败！',
            type: 'error',
          })
          this.loadPost()
        }
      })
    }
  },
  beforeMount() {
    this.loadPost()
  }
}
</script>

<style scoped>
.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}

.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}

.layout-container-demo .el-menu {
  border-right: none;
}

.layout-container-demo .el-main {
  padding: 0;
}

.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
}
</style>
